#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

#define PORT 8081

int main() {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        std::cout << "socket error " << std::endl;
        return 1;
    }
    std::cout << sockfd << std::endl;
   struct sockaddr_in local;
   memset(&local, 0, sizeof(local));
   local.sin_family = AF_INET;
   local.sin_port = htonl(PORT);
   // 云服务器绑定ip的时候，一般不能直接绑定明确的ip；
   // 使用INADDR_ANY来绑定机器上所有的ip
   // ip点分十进制转4字节形式：inet_addr
   local.sin_addr.s_addr = htonl(INADDR_ANY);
   if (bind(sockfd,(struct sockaddr*)&local, sizeof(local)) < 0) {
       std::cerr << "bind error" << std::endl;
       return 1;
   }

   char message[1024];
   for ( ; ; ) {
       struct sockaddr_in peer;
       socklen_t len = sizeof(peer);
       ssize_t s = recvfrom(sockfd, message, sizeof(message)-1, 0, (struct sockaddr*)&peer, &len);
       if (s > 0) {   
          message[s] = '\0';
          std::cout << "client -> server(server): " <<  message << std::endl;
          sendto(sockfd, message, strlen(message), 0, (struct sockaddr*)&peer, len);
       } else {
           //TODO
       }
   }

   close(sockfd);
    return 0;
}
